package com.zhoukx.netty.simple;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class NettyClient {

    public static void main(String[] args) throws InterruptedException {

        // 客户单需要一个时间循环组
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
        try {


            // 创建客户端启动对象
            // 注意客户端视同的不是ServerBootstrap 而不是BootStrap
            Bootstrap bootstrap = new Bootstrap();

            // 设置相关的参数
            bootstrap.group(eventExecutors)  // 设置线程组
                    .channel(NioSocketChannel.class)  // 设置客户端通道的实现诶
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new NettyClientHandler());
                        }
                    });

            System.out.println("客户端 ok...");

            // 启动客户端去连接服务端
            // 关于ChannelFuture 要分析,设计到netty的异步模型
            ChannelFuture sync = bootstrap.connect("127.0.0.1", 6668).sync();
            // 关闭通道进行监听
            sync.channel().closeFuture().sync();
        } catch (Exception e) {
           eventExecutors.shutdownGracefully();
        }
    }

}
